package com.nand.module.function.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.animation.ScaleInAnimation;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.zxing.activity.CaptureActivity;
import com.nand.library.zxing.activity.CodeUtils;
import com.nand.module.function.R;
import com.nand.module.function.adapter.ClampingAdapter;
import com.nand.module.function.adapter.MMMAdapter;
import com.nand.module.function.bean.ClampingBean;
import com.nand.module.function.bean.IqcListBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.function.utils.SpacesItemDecoration;
import com.nand.module.function.view.CustomPartShadowPopupView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.header.FalsifyHeader;
import com.scwang.smartrefresh.layout.header.TwoLevelHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * created by 86185
 * on 2020/2/7
 */

@Route(path = "/function/clamping/list")
public class ClampingActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView mRecycler;
    private ClampingAdapter mAdapter;
    private SmartRefreshLayout swipeRefres;
    private HttpParams param;
    private int page;//加载页数
    private List<ClampingBean> list = new ArrayList<>();
    private EditText mEtFixtureCode;
    private CheckBox cbResult;//状态
    private RelativeLayout relativeLayout;//筛选布局
    private RelativeLayout relativeLayoutState;//筛选布局（状态）
    private int resultPosition = 0;//状态默认选择position
    private String[] resultData;//数据
    private CustomPartShadowPopupView popupViewResult;

    @Override
    protected int initLayout() {
        return R.layout.activity_clamping;
    }
    @Override
    protected boolean isActionBar() {
        return true;
    }
    private static final int REQUEST_CODE3 = 1003;
    @Override
    protected void initView() {
        page = 1;
        mActionBar().setCenterText("工装台账");
        resultData = getResources().getStringArray(R.array.tooling_state_list);

        findViewById(R.id.iv_or_code).setOnClickListener(this);
        mEtFixtureCode = findViewById(R.id.et_fixture_code);
        findViewById(R.id.tv_query).setOnClickListener(this);
        mRecycler = findViewById(R.id.recycler);
        cbResult = findViewById(R.id.cb_result);
        relativeLayout = findViewById(R.id.relative_2);
        relativeLayoutState = findViewById(R.id.relative_state);
        swipeRefres = findViewById(R.id.swipe_refres);
        swipeRefres.autoRefresh();
        //swipeRefres.setEnableRefresh(true);//是否启用下拉刷新功能
        // swipeRefres.setEnableLoadMore(true);//是否启用上拉加载功能
        // swipeRefres.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        swipeRefres.setRefreshHeader(new ClassicsHeader(this));
        swipeRefres.setRefreshFooter(new ClassicsFooter(this));
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ClampingAdapter(this);
        mRecycler.setAdapter(mAdapter);
        int space = 15;
        mRecycler.addItemDecoration(new SpacesItemDecoration(space));
        mAdapter.setOnItemClickListener(new ClampingAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int fixtureState = list.get(position).getFixtureState();
                String oid = list.get(position).getOid();
                Intent intent2 = new Intent(ClampingActivity.this, ClampingDetalisActivity.class);
                Bundle bundle2 = new Bundle();
                bundle2.putInt("type", fixtureState);
                bundle2.putString("fFixtureOid", oid);
                intent2.putExtras(bundle2);
                startActivityForResult(intent2, REQUEST_CODE3);
            }
        });

        swipeRefres.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                //String string = mEtFixtureCode.getText().toString();
                page = 1;
                param = new HttpParams();
                //if (0 < string.length()){
                 //   param.put("fixtureCode", string);
                //}else {

               // }

               // down(false);
                selectListCondition(false);
            }
        });
        swipeRefres.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                page++;
                param = new HttpParams();
                //down(false);
                selectListCondition(false);
            }
        });
        cbResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupViewResultList(view,resultData,getResources().getString(R.string.sx_zt));
            }
        });
    }

    private void down(final boolean isFirst) {
        Log.e(TAG, "down: ----param--"+param);
        OkGoUtils.getInstance().post(this, URL.QUERY_TB_EQ_FIXTURE, param, 1, false, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (response.getCode() == 200) {
                    String data = response.getDataInfo().toString();
                    LogUtils.e("avv=======" + data);
                    swipeRefres.finishLoadMore();
                    if (!isFirst)
                        swipeRefres.finishRefresh();
                    List<ClampingBean> clampingBeans = JSON.parseArray(data, ClampingBean.class);
                    if (page != 1) {
                        if (clampingBeans == null || clampingBeans.size() == 0) {
                            swipeRefres.finishLoadMoreWithNoMoreData();
                        }
                    } else {
                        list.clear();
                        swipeRefres.finishRefresh();
                    }
                    for (ClampingBean bean : clampingBeans) {
                            list.add(bean);
                    }

                    mAdapter.setData(list);
                } else {
                    showToast(response.getMsg());
                }
            }
            @Override
            public void onError(Throwable e, int id) {
            }
        });
    }
    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list(点巡结果,故障类别,保养状态，设备状态)
     */
    private void showPopupViewResultList(View view, String[] data, final String value){
        if(popupViewResult==null){
            popupViewResult = (CustomPartShadowPopupView) new XPopup.Builder(activity)
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbResult.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(activity));
            popupViewResult.setStringData(data, null);
            popupViewResult .setCheckedPosition(resultPosition);
            popupViewResult .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    resultPosition = position;
                    cbResult.setText(position == 0 ?value:text);
                    page = 1;
                    selectListCondition(true);
                }
            });
        }
        popupViewResult.show();
    }
    /**
     *  @author ljp
     *  @time   10:06
     *  @describe 根据筛选条件查询数据
     */
    private void selectListCondition(boolean isFirst){
        param.clear();
        param.put("current", String.valueOf(page));
        param.put("size", "10");
        String s = mEtFixtureCode.getText().toString();
        if(!TextUtils.isEmpty(s)) {
            if (resultPosition > 0) {
                //if (typePosition > 0) {
                  //  paramsPost.put("result", resultPosition - 1);
                  //  paramsPost.put("type", typePosition - 1);
                   // paramsPost.put("equipID", s);
              //  }else {
                    param.put("state", resultPosition - 1);
                param.put("fixtureCode", s);
               // }
            }
        }else {
            if (resultPosition > 0) {
                //if (typePosition > 0) {
                //    paramsPost.put("result", resultPosition - 1);
                //    paramsPost.put("type", typePosition - 1);
                //}else {
                param.put("state", resultPosition - 1);
                //}
            }

        }
        down(isFirst);
    }

    @Override
    protected void initData() {
        param = new HttpParams();
        param.put("current", "1");
        param.put("size", "10");
        down(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    final String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtFixtureCode.setText(result);
                    LogUtils.e("22222result===" + result);
//                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(ClampingActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        } else if (requestCode == REQUEST_CODE3 && 0 != resultCode) {
            param = new HttpParams();
            page = 1;
            param.put("current", page);
            param.put("size", "10");
            //down(true);
            selectListCondition(true);
        }
    }

    private static final int REQUEST_CODE = 1001;

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_or_code){
            Intent intent = new Intent(ClampingActivity.this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }else if (id == R.id.tv_query){
            //String s = mEtFixtureCode.getText().toString();
            param = new HttpParams();
            page = 1;
           // param.put("fixtureCode", s);

            //if (0 < s.length()){
              //  param.put("fixtureCode", s);
           // }else {
                param.put("current", String.valueOf(page));
                param.put("size", "10");
           // }
           // down(true);
            selectListCondition(false);
        }
    }

}
